// components/colorPicker/colorPicker.js
var ctx = null,
  x = 0,
  y = 0,
  canvasWidth = 375,
  canvasHeight = 375;


Component({
  /**
   * 组件的属性列表
   */
  properties: {
    selectedcolor: {
      type: String,
      value: 'rgb(255,225,0)',
      // observer:function(newValue,oldValue){

      // }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    transparentBg64: '',

  },
  attached() {
    let {
      selectedcolor
    } = this.data,
      hsvColor = this.rgb2hsv(selectedcolor);
    this.hue = this.hsv2rgb(hsvColor.h, 100, 100);
    let rgbaColor = selectedcolor.split(','),
      rgba = {};    
    if (rgbaColor[0].split('(')[0] == 'rgba') {
      rgba.r = parseInt(rgbaColor[0].split('(')[1]);
      rgba.g = parseInt(rgbaColor[1]);
      rgba.b = parseInt(rgbaColor[2]);
      rgba.a = parseFloat(rgbaColor[3].split(')')[0]).toFixed(2);
    } else {
      rgba.r = parseInt(rgbaColor[0].split('(')[1]);
      rgba.g = parseInt(rgbaColor[1]);
      rgba.b = parseInt(rgbaColor[2].split(')')[0]);
      rgba.a = 1
    }
    console.log(selectedcolor, rgba, hsvColor)
    this.setData({
      hueDeg: hsvColor.h,      
      rgba
    })
    this.x = Math.round(hsvColor.s * 3.74)
    this.y = Math.round((100 - hsvColor.v) * 3.74)

    console.log(x, y)
    var query = this.createSelectorQuery()
    query.select('.color-palette')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        let canvas = res[0].node,
          ctx = canvas.getContext('2d'),

          {
            pixelRatio
          } = wx.getSystemInfo()
        this.canvasWidth = 375
        this.canvasHeight = 375
        this.ctx = ctx
        canvas.width = canvasWidth
        canvas.height = canvasHeight
        ctx.scale(pixelRatio, pixelRatio)
        this.draw(this.hue, this.x, this.y)



      })
  },

  /**
   * 组件的方法列表
   */
  methods: {

    draw: function (hue, x, y) {
      let ctx = this.ctx,
        canvasWidth = this.canvasWidth,
        canvasHeight = this.canvasHeight

      ctx.save()
      ctx.fillStyle = hue;
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);
      ctx.restore();
      //白色渐变，从左至右
      ctx.save()
      var wg = ctx.createLinearGradient(0, 0, canvasWidth, 10);
      wg.addColorStop(0, 'rgba(255,255,255,1)');
      wg.addColorStop(1, 'rgba(255,255,255,0)');
      ctx.fillStyle = wg;
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);
      ctx.restore();
      //黑色渐变，从上到下
      var bg = ctx.createLinearGradient(0, 0, 10, canvasHeight);
      bg.addColorStop(0, 'rgba(0,0,0,0)');
      bg.addColorStop(1, 'rgba(0,0,0,1)');
      ctx.fillStyle = bg;
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);
      ctx.restore();

      //选中颜色
      ctx.save()
      ctx.beginPath();
      ctx.arc(x, y, 15, 0, 2 * Math.PI);
      ctx.strokeStyle = '#ffffff'
      ctx.lineWidth = 3;
      ctx.stroke();
      ctx.restore();

      let imageData = ctx.getImageData(x, y, 1, 1),
        pixel = imageData.data,
        r = pixel[0],
        g = pixel[1],
        b = pixel[2]

      this.setData({
        'rgba.r':r,
        'rgba.g':g,
        'rgba.b':b,
      //  'rgba.a':
        selectedcolor: `rgba(${r},${g},${b},${this.data.rgba.a})`
      })
    },

    start(e) {

    
      const {
        x,
        y
      } = e.touches[0];
      //   console.log(x, y)
      this.x = Math.floor(x / 0.85)
      this.y = Math.floor(y / 0.85)

      if (this.x <= 0) {
        this.x = 0
      }
      if (this.y <= 0) {
        this.y = 0
      }
      if (this.x >= this.canvasWidth) {
        this.x =  Math.floor(this.canvasWidth)-1 
      }
      if (this.y >= this.canvasHeight) {
        this.y = Math.floor(this.canvasHeight)-1 
      }
      // console.log(this.x, this.y)
      this.draw(this.hue, this.x, this.y)


    },
    move(e) {
      this.start(e)
    },
    end(e) {

      // this.setData({
      //   selectedColor: this.selectedColor
      // })
    },
    changeHue(e) {
      // console.log(e.detail.value)
      let hueDeg = e.detail.value
      let hue = this.hsv2rgb(hueDeg, 100, 100)
      this.hue = hue
      this.draw(hue, this.x, this.y);
      this.setData({
        hueDeg,
        selectedcolor: `rgba(${this.data.rgba.r},${this.data.rgba.g},${this.data.rgba.b},${this.data.rgba.a})`
      })


    },
    changeAlpha(e) {
      this.setData({
        'rgba.a': e.detail.value.toFixed(2),
        selectedcolor: `rgba(${this.data.rgba.r},${this.data.rgba.g},${this.data.rgba.b},${this.data.rgba.a})`
      })
    },
    hsv2rgb: function (h, s, v) {
      let hsv_h = (h / 360).toFixed(2);
      let hsv_s = (s / 100).toFixed(2);
      let hsv_v = (v / 100).toFixed(2);

      var i = hsv_h * 6;
      var f = hsv_h * 6 - i;
      var p = hsv_v * (1 - hsv_s);
      var q = hsv_v * (1 - f * hsv_s);
      var t = hsv_v * (1 - (1 - f) * hsv_s);

      var rgb_r = 0,
        rgb_g = 0,
        rgb_b = 0;
      switch (Math.floor(i % 6)) {
        case 0:
          rgb_r = hsv_v;
          rgb_g = t;
          rgb_b = p;
          break;
        case 1:
          rgb_r = q;
          rgb_g = hsv_v;
          rgb_b = p;
          break;
        case 2:
          rgb_r = p;
          rgb_g = hsv_v;
          rgb_b = t;
          break;
        case 3:
          rgb_r = p;
          rgb_g = q;
          rgb_b = hsv_v;
          break;
        case 4:
          rgb_r = t;
          rgb_g = p;
          rgb_b = hsv_v;
          break;
        case 5:
          rgb_r = hsv_v, rgb_g = p, rgb_b = q;
          break;
      }

      return 'rgb(' + (Math.floor(rgb_r * 255) + "," + Math.floor(rgb_g * 255) + "," + Math.floor(rgb_b * 255)) + ')';
    },
    rgb2hsv: function (color) {
      let rgb = color.split(',');
      let R = parseInt(rgb[0].split('(')[1]);
      let G = parseInt(rgb[1]);
      let B = parseInt(rgb[2].split(')')[0]);

      let hsv_red = R / 255,
        hsv_green = G / 255,
        hsv_blue = B / 255;
      let hsv_max = Math.max(hsv_red, hsv_green, hsv_blue),
        hsv_min = Math.min(hsv_red, hsv_green, hsv_blue);
      let hsv_h, hsv_s, hsv_v = hsv_max;

      let hsv_d = hsv_max - hsv_min;
      hsv_s = hsv_max == 0 ? 0 : hsv_d / hsv_max;

      if (hsv_max == hsv_min) hsv_h = 0;
      else {
        switch (hsv_max) {
          case hsv_red:
            hsv_h = (hsv_green - hsv_blue) / hsv_d + (hsv_green < hsv_blue ? 6 : 0);
            break;
          case hsv_green:
            hsv_h = (hsv_blue - hsv_red) / hsv_d + 2;
            break;
          case hsv_blue:
            hsv_h = (hsv_red - hsv_green) / hsv_d + 4;
            break;
        }
        hsv_h /= 6;
      }
      return {
        h: (hsv_h * 360).toFixed(),
        s: (hsv_s * 100).toFixed(),
        v: (hsv_v * 100).toFixed()
      }
    },
  }
})